<template>
	<div id="dashboard">
		<!-- 左侧栏 vue优化-->
		<div id="colLeft"></div>
		<!-- 中间区域 -->
		<div id="colCenter">
			<!-- 标题 -->
			<div id="header">
				<!--				<img class="header-title" src="src/assets/img/header-title.png" />-->
				<p class="header-title">设备监控</p>
			</div>
			<!-- 核心图表区 -->
			<div id="container">
				<!-- 左侧图表 -->
				<div id="conLeft">
					<div class="chart-panel">
						<div class="chart-title">
							<span class="title">当天湿度</span>
						</div>
						<!--						<LeftTop></LeftTop>-->
						<div class="chart-div">
							<div class="chart-loader">
								<!--								<div class="loader"></div>-->
								<div class="panel-con">
									<div :ref="'chartRef' + prefix[2]" style="width: 100%; z-index: 999; height: 250px"></div>
								</div>
							</div>
						</div>
					</div>
					<div class="chart-panel chart-panel-multi">
						<div class="chart-title">
							<span class="title">当天温度</span>
						</div>
						<div class="chart-div">
							<div class="chart-loader">
								<!--									<div class="loader"></div>-->
								<div class="panel-con">
									<div :ref="'chartRef' + prefix[1]" style="width: 100%; z-index: 999; height: 250px"></div>
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 中间图表 -->
				<div id="conCenter">
					<!-- 统计指标 -->
					<div id="countIndicator" class="indicator-panel">
    					<div v-for="(item, index) in indicators" :key="index" class="indicator-div">
        				<div :class="'indicator indicator-' + (index + 1)">
            			<p>
                			<span :id="'#' + (index + 1)" v-if="item.name !== '控温舵机'">{{ item.value }}</span>
                			<span :id="'#' + (index + 1)" v-else @click="handleClick(item)">{{ item.value }}</span>
            			</p>
            			<p>{{ item.name }}</p>
        			</div>
    			</div>
</div>


					<!-- 地图 -->
					<div class="map-panel">
						<div class="map-circle">
							<div class="map-circle-inner"></div>
						</div>
						<div id="mapDiv" class="map-div"></div>
					</div>
					<!-- 右侧图表 -->
					<div id="conRight">
						<div class="chart-panel">
							<div class="chart-title">
								<span class="title">当天光感亮度</span>
							</div>
							<div class="chart-div">
								<div class="chart-loader">
									<!--									<div class="loader"></div>-->
									<div class="panel-con">
										<div :ref="'chartRef' + prefix[0]" style="width: 100%; z-index: 999; height: 250px"></div>
									</div>
								</div>
							</div>
						</div>
						<div class="chart-panel chart-panel-multi">
							<div class="chart-title">
								<ul class="chart-tab">
									<li class="active"><a href="#">当天平均参数值</a></li>
									<!-- <li><a href="#">图表 B</a></li> -->
								</ul>
							</div>
							<div id="" class="chart-div" style="margin: 10px; height: 320px">
								<div class="chart-loader">
									<div ref="paramAverage" style="margin-top:  width: 100%; z-index: 999; height: 250px"></div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 右侧栏 -->
		<div id="colRight">
			<div v-for="(tab, index) in rightTabs" :key="index" class="panel-div">
				<div class="panel-title">
					<ul class="panel-tab">
						<li v-for="(item, i) in tab" :key="i" :class="{ active: i === 0 }">
							<a :href="item.href">{{ item.text }}</a>
						</li>
					</ul>
				</div>
				<div class="panel-con"></div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import service from '@/utils/request'
import { closeWebSocket, initWebSocket, sendWebSocket, data } from './websocket'
import { done } from 'nprogress'
import axios from 'axios'
import mqttService from '@/utils/mqttService'

//指标
const indicators = ref([
	{ name: '温度', value: 0 },
	{ name: '湿度', value: 0 },
	{ name: '亮度', value: 0 },
	{ name: '控温舵机', value: '开' },
])
//x轴
const xAxle = ref([])
// y轴数据
const temAxle = ref([])
const humAxle = ref([])
const brightnessStatusAxle = ref()
//数据获取
const deviceData = () => {
	service.post('/deviceStatus/queryOneDay', {}).then(res => {
		//收拢
		brightnessStatusAxle.value = res.data.map((res: { deviceBrightness: any }) => +res.deviceBrightness)
		humAxle.value = res.data.map((res: { deviceTemperature: number }) => +res.deviceTemperature)
		temAxle.value = res.data.map((res: { deviceHumidity: number }) => +res.deviceHumidity)
		params.value?.push(calculateAverage(brightnessStatusAxle.value))
		params.value?.push(calculateAverage(humAxle.value))
		params.value?.push(calculateAverage(temAxle.value))
		paramAverageOption.value = {
			series: [
				{
					type: 'pie',
					data: [
						{
							value: params.value[0],
							name: '当天温度平均值: ' + params.value[0],
							itemStyle: {
								color: 'rgb(0, 0, 128)'
							}
						},
						{
							value: params.value[1],
							name: '当天气候湿度平均值: ' + params.value[1],
							itemStyle: {
								color: 'rgb(192, 192, 192 )'
							}
						},
						{
							value: params.value[2],
							name: '当天光感强度平均值: ' + params.value[2],
							itemStyle: {
								color: 'rgb(173, 216, 230)'
							}
						}
					],
					roseType: 'area'
				}
			]
		}
		const chartInstanceParams = echarts.init(paramAverage.value)
		chartInstanceParams?.setOption(paramAverageOption.value)
		console.log('打印第一个参数', params.value[0])

		//x轴收拢
		xAxle.value = res.data.map((res: { deviceIntoTime: any }) => formatTime(res.deviceIntoTime))
	})
}
//时间格式化
function formatTime(dateString: any) {
	const date = new Date(dateString)
	const year = date.getFullYear()
	const day = date.getDate() // 获取日期中的日
	const hour = date.getHours() // 获取小时
	const minute = date.getMinutes() // 获取分钟
	// 根据需要的格式拼接时间字符串
	const formattedTime = `${year}${day} ${hour}:${minute}`
	return formattedTime
}
//求平均值
function calculateAverage(array: number[]) {
	if (array.length === 0) {
		return 0
	}

	const sum = array.reduce((acc: number, val: number) => acc + val, 0)
	const average = sum / array.length
	return average
}
//表格
const prefix = ref(['First', 'Second', 'Third'])
const chartRefFirst = ref(null)
const chartOptions = ref({
	xAxis: {
		data: xAxle.value == [] ? ['A', 'B', 'C'] : xAxle.value
	},
	yAxis: {
		name: '亮度视图'
	},
	series: [
		{
			data: brightnessStatusAxle.value,
			type: 'line',
			smooth: true,
			areaStyle: {
				color: 'rgb(250, 236, 199)',
				opacity: 0.5
			}
		}
	]
})
const chartRefSecond = ref(null)
const chartOptionsSecond = ref({
	xAxis: {
		data: xAxle.value == [] ? ['A', 'B', 'C'] : xAxle.value
	},
	yAxis: {
		name: '温度视图'
	},
	series: [
		{
			data: temAxle.value == null ? [10, 22, 23, 19] : temAxle.value.slice(),
			type: 'line',
			smooth: false,
			areaStyle: {
				color: 'rgb(250, 236, 199)',
				opacity: 0.5
			}
		}
	]
})
//玫瑰图
const params = ref([])
const paramAverage = ref(null)
const paramAverageOption = ref({})

const chartRefThird = ref(null)
const chartOptionsThird = ref({
	xAxis: {
		data: xAxle.value == [] ? [] : xAxle.value
	},
	yAxis: {
		name: '当天湿度'
	},
	series: [
		{
			data: humAxle.value == [] ? [] : humAxle.value, // 替换为您的数据
			type: 'line',
			smooth: true,
			areaStyle: {
				color: 'rgb(250, 236, 199)',
				opacity: 0.5
			}
		}
	]
})
// 监听器实事更新
let msg = ref('测试数据')
watch(
	() => xAxle.value,
	newVal => {
		// 更新 chartOptions 中的 xAxis.data
		chartOptions.value.xAxis.data = newVal
		chartOptionsSecond.value.xAxis.data = newVal
		chartOptionsThird.value.xAxis.data = newVal

		// 更新光感数据
		chartOptions.value.series[0].data = brightnessStatusAxle.value == null ? [10, 22, 23, 19] : brightnessStatusAxle.value.slice()
		// 更新温度数据
		chartOptionsSecond.value.series[0].data = temAxle.value == null ? [10, 22, 23, 19] : temAxle.value.slice()
		// 更新第三个表格数据
		chartOptionsThird.value.series[0].data = humAxle.value == null ? [10, 22, 23, 19] : humAxle.value.slice()

		renderChart()
	}
)

// 
let deviceStatus = ref(true)
watch(data, (newVal, oldVal) => {
	console.log('打印新的对象', newVal)

	if (data.value != null) {
		const jsonData = JSON.parse(data.value)
		console.log('打印json提取到的温度', jsonData.deviceTemperature)
		
		indicators.value[0].value = jsonData.deviceTemperature ?? indicators.value[0].value
		indicators.value[1].value = jsonData.deviceHumidity ?? indicators.value[1].value
		indicators.value[2].value = jsonData.deviceBrightness ?? indicators.value[2].value
		// const tem = deviceStatus.value == true ? 1 : 0
		indicators.value[3].value = deviceStatus.value  ? '开' : '关'
		console.log(indicators.value[3].value+"-------------");
		

		msg.value = jsonData
	}
})

const renderChart = () => {
	const chartInstance = echarts.init(chartRefFirst.value)
	chartInstance?.setOption(chartOptions.value)

	const chartInstanceSecond = echarts.init(chartRefSecond.value)
	chartInstanceSecond?.setOption(chartOptionsSecond.value)

	const chartInstanceThird = echarts.init(chartRefThird.value)
	chartInstanceThird?.setOption(chartOptionsThird.value)

	const chartInstanceParams = echarts.init(paramAverage.value)
	chartInstanceParams?.setOption(paramAverageOption.value)
}

onMounted(() => {
	deviceData()
	connectMsg()
	nextTick(() => {
		const chartInstance = echarts.init(chartRefFirst.value)
		chartInstance?.setOption(chartOptions.value)

		const chartInstanceSecond = echarts.init(chartRefSecond.value)
		chartInstanceSecond?.setOption(chartOptionsSecond.value)

		const chartInstanceThird = echarts.init(chartRefThird.value)
		chartInstanceThird?.setOption(chartOptionsThird.value)
		setTimeout(() => {
			console.log('打印挂载时para: ', params.value)
			const chartInstanceParams = echarts.init(paramAverage.value)
			chartInstanceParams?.setOption(paramAverageOption.value)
		}, 100)
	})
	setTimeout(() => {
		senMsg()
	}, 1000)
})

//连接设备  （具体路径和后端规定）
function connectMsg() {
	const toIp = `ws://127.0.0.1:19999/msg`
	initWebSocket(toIp)
}

// 设备断开
function closeWs() {
	closeWebSocket()
}

//提交参数
function senMsg() {
	sendWebSocket('发送测试数据')
}
function handleClick(item:any){
	console.log("click : ",deviceStatus.value);
	
	deviceStatus.value = !deviceStatus.value
		
		// const tem = deviceStatus.value == true ? 1 : 0
	indicators.value[3].value = deviceStatus.value  ? '开' : '关'
	console.log(indicators.value[3].value+"-------------");
	//send mqtt publish
	const data = { deviceStatus: deviceStatus.value }
	// service.post('/device/sendMessage',data).then(res => {
	// 	console.log("send success");
		
	// })
	// axios.post("127.0.0.1:8847/sendMessage",data).then(res => {
	// 	console.log("send success",res);
	// })
	mqttService.post('/device/sendMessage',data).then(res => {
		console.log("send success",res);	
	})
}

//初始化弹窗功能
const dialogVisible = ref(false)
const showDeviceSelectionDialog = () => {
	dialogVisible.value = true
}
const selectDeviceAndConnect = () => {
	// 在这里添加选择设备并连接的逻辑
	// 连接成功后关闭弹窗
	dialogVisible.value = false
}

const handleClose = () => {
	// 在对话框关闭前执行的逻辑，比如清理工作
	done()
}


</script>
